package book;

import constant.Constant;
import utils.AnalyzingBook;
import utils.ScannerSingleton;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

public class Library {
    public Book[] books; // 图书数组
    public int bookCount; // 图书的数量
    private final AnalyzingBook analyzingBook = new AnalyzingBook();

    public Scanner scanner;
    private static Library library;

    private Library(){
        loadAllBook();
        scanner = ScannerSingleton.getInstance();
    }

    public static Library getInstance(){
        if(library == null){
            library = new Library();
        }

        return library;
    }

    private void loadAllBook(){
        try {
            Book[] allBooks = analyzingBook.loadBook(Constant.ALL_BOOK_NAME_FILE);
            books = new Book[Constant.CAPACITY];
            if(allBooks == null){
                bookCount = 0;
            }else {
                int allBookLen = allBooks.length;
                if(allBookLen > books.length){
                    books = new Book[allBookLen];
                }

                for (int i = 0; i < allBookLen; i++) {
                    books[i] = allBooks[i];
                }

                bookCount = allBookLen;
            }

        }catch (IOException e){
            throw new RuntimeException();
        }
    }

    private void storeAllBook(){
        try {
            analyzingBook.storeBook(books, Constant.ALL_BOOK_NAME_FILE);
        }catch (IOException e){
            throw new RuntimeException();
        }

    }

    // --------------------------------AdminUser---------------------------------

    // 上架图书
    public void addBook(Book book){
        loadAllBook();
        System.out.println("Library类addBook方法执行了");
        if(bookCount >= books.length){
            System.out.println("图书馆已满, 无法上架更多图书");
            // 可以扩容
            return;
        }

        books[bookCount] = book;
        if(bookCount == 0){
            book.setBookId(1);
        }else {
            Book bookLast = books[bookCount-1];
            book.setBookId(bookLast.getBookId()+1);
        }
        bookCount++;
        storeAllBook();

        System.out.println("图书 " + book.getTitle() + "上架成功!");
    }

    // 修改图书
    public void updateBook(Book book){
        // 先找到该书是哪个下标
        int index = searchByIdReturnIndex(book.getBookId());
        books[index] = book;
        // 一定要进行存储
        storeAllBook();
        System.out.println("更新成功!");
    }

    // 根据bookId 返回 书籍索引位置
    private int searchByIdReturnIndex(int bookId){
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId() == bookId){
                return i;
            }
        }
        return -1;
    }

    // 删除书籍
    public void removeBook(int bookId){
        int index = searchByIdReturnIndex(bookId);
        for (int i = index; i < bookCount-1; i++) {
            books[i] = books[i+1];
        }
        books[bookCount-1] = null;

        storeAllBook();

        bookCount--;
    }

    // 统计每本书的借阅次数
    public void borrowCount(){
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书名: "+ book.getTitle() + " 借阅次数: " + book.getBorrowCount());
        }
    }

    // 查询最受欢迎的前n本书
    public void generateBook(int k){
        //1. 加载已有的全部书籍
        loadAllBook();
        //2. 把所有书籍放在 临时数据 进行排序
        Book[] tmp = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            tmp[i] = books[i];
        }

        //2.1 开始排序
        Arrays.sort(tmp);

        //3. 把前k本书拷贝到新数组   可以不定义临时数组, 直接输出k个就行
        Book[] generateBooks = new Book[k];
        for (int i = 0; i < k; i++) {
            generateBooks[i] = tmp[i];
        }

        //4. 打印新数组
        System.out.println("最受欢迎书籍如下: ");
        for (int i = 0; i < generateBooks.length; i++) {
            Book book = generateBooks[i];
            System.out.println("索引:"+i+" 书名: "+ book.getTitle()+" 作者: "+book.getAuthor()+" 借阅次数: "+book.getBorrowCount());
        }
    }

    // 查看库存状态
    public void checkInventoryStatus(){
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String status = book.isBorrowed() ? "已借出" : "在馆";
            System.out.println("书名: "+book.getTitle() + " 目前状态: "+status);
        }
    }

    // 并移除上架超过一年的图书
    public void checkAndRemoveOldBooks(){
        loadAllBook();

        // 获取当前时间戳 LocalDate
        long currentTimestamp = System.currentTimeMillis();

        // 将当前时间戳转换为 LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        boolean flg = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];

            // 获取当前书籍的上架时间d
            LocalDate specifiedDate = book.getLocalDate();

            // 计算两个日期之间的差值(以年为单位)
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate, currentDate);

            if (yearsBetween >= 1){
                System.out.println("图书 " + book.getTitle() + " 已经上架超过一年, 是否移除? (y/n): ");

                scanner.nextLine();
                String response = scanner.nextLine();
                if(response.equalsIgnoreCase("y")){
                    // 确认删除 调用remove方法进行删除
                    removeBook(book.getBookId());
                    i--; // 因为后面的书已经向前移动, 所以要重新检查当前索引位置
                }
                flg = true;
            }
        }
        if(!flg){
            System.out.println("没有上架超过一年的图书! ");
        }
    }

    public void exit(){
        System.out.println("退出系统");
        System.exit(0);
    }

    // --------------------------------NormalUser---------------------------------

    // 归还图书
    public void returnBook(int bookId){
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId() == bookId){
                book.setBorrowed(false);
                book.decreaseBorrowCount();
            }
        }
        storeAllBook();
    }


    public void searchBook() {
        scanner.nextLine();
        System.out.println("请输入你要查找的图书名称: ");
        String title = scanner.nextLine();
        Book book = search(title);
        if(book == null){
            System.out.println("没有你要找的这本书, 你查找的书名为: "+title);
        }else {
            System.out.println("找到了你要查找的书, 书的详细信息如下: ");
            System.out.println(book);
        }
    }

    private Book search(String title) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(books[i].getTitle().equals(title)){
                return book;
            }
        }
        return null;
    }


    public void displayBooks() {
        System.out.println("显示图书:");
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }

    public Book searchById(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId() == bookId){
                return books[i];
            }
        }
        return null;
    }

    // 借阅图书
    public void borrowBook(int bookId) {
        Book book = searchById(bookId);
        book.setBorrowed(true);
        book.incrementBorrowCount();
        storeAllBook();
    }
}
